{% extends theme_path('admin/base.html') %}

{% block title %}网站配置{% endblock %}

{% block head %}
<!-- 如果基础模板中没有引入 Alpine.js，在这里引入 -->
<script defer src="{{ url_for('static', filename='default/vendor/alpinejs3.14.3.js') }}"></script>
{% endblock %}

{% block content %}
<div class="container mx-auto px-4 py-8">
    <div class="bg-white rounded-lg shadow-sm">
        <div class="px-6 py-4 border-b">
            <h2 class="text-xl font-bold">网站配置</h2>
        </div>
        <div class="p-6">
            <form method="post" class="space-y-8" id="configForm" onsubmit="return handleSubmit(event)">
                <input type="hidden" name="csrf_token" value="{{ csrf_token() }}">
                
                <!-- 基本设置 -->
                <div class="space-y-6">
                    <h3 class="text-lg font-medium text-gray-900">基本设置</h3>
                    {% for config in configs %}
                        {% if config.key in ['site_name', 'site_keywords', 'site_description', 'contact_email', 'icp_number', 'footer_text'] %}
                        <div>
                            <label class="block text-sm font-medium text-gray-700 mb-2">
                                {{ config.description }}
                            </label>
                            <input type="text" name="config_{{ config.key }}" value="{{ config.value }}"
                                   class="w-full px-3 py-2 border rounded-lg focus:outline-none focus:ring-2 focus:ring-blue-500">
                        </div>
                        {% endif %}
                    {% endfor %}
                </div>

                <!-- API设置 -->
                <div class="space-y-6">
                    <h3 class="text-lg font-medium text-gray-900">API设置</h3>
                    
                    <!-- 启用API -->
                    <div>
                        <label class="block text-sm font-medium text-gray-700 mb-2">
                            是否启用API
                        </label>
                        <select name="config_enable_api" 
                                class="w-full px-3 py-2 border rounded-lg focus:outline-none focus:ring-2 focus:ring-blue-500">
                            <option value="true" {% if configs|selectattr('key', 'equalto', 'enable_api')|first|attr('value') == 'true' %}selected{% endif %}>启用</option>
                            <option value="false" {% if configs|selectattr('key', 'equalto', 'enable_api')|first|attr('value') != 'true' %}selected{% endif %}>禁用</option>
                        </select>
                    </div>

                    <!-- Token验证 -->
                    <div>
                        <label class="block text-sm font-medium text-gray-700 mb-2">
                            是否需要Token验证
                        </label>
                        <select name="config_api_token_required" 
                                class="w-full px-3 py-2 border rounded-lg focus:outline-none focus:ring-2 focus:ring-blue-500">
                            <option value="true" {% if configs|selectattr('key', 'equalto', 'api_token_required')|first|attr('value') == 'true' %}selected{% endif %}>是</option>
                            <option value="false" {% if configs|selectattr('key', 'equalto', 'api_token_required')|first|attr('value') != 'true' %}selected{% endif %}>否</option>
                        </select>
                    </div>

                    <!-- API Token -->
                    <div>
                        <label class="block text-sm font-medium text-gray-700 mb-2">
                            API Token
                        </label>
                        <div class="flex space-x-2">
                            <input type="text" name="config_api_token" 
                                   value="{{ configs|selectattr('key', 'equalto', 'api_token')|first|attr('value') }}"
                                   class="flex-1 px-3 py-2 border rounded-lg focus:outline-none focus:ring-2 focus:ring-blue-500">
                            <button type="button" onclick="generateToken()"
                                    class="px-4 py-2 bg-teal-400 text-white rounded-lg hover:bg-teal-500">
                                生成新Token
                            </button>
                        </div>
                    </div>

                    <!-- 请求频率限制 -->
                    <div>
                        <label class="block text-sm font-medium text-gray-700 mb-2">
                            API请求频率限制(次/分钟)
                        </label>
                        <input type="number" name="config_api_rate_limit" 
                               value="{{ configs|selectattr('key', 'equalto', 'api_rate_limit')|first|attr('value') }}"
                               min="1" max="1000"
                               class="w-full px-3 py-2 border rounded-lg focus:outline-none focus:ring-2 focus:ring-blue-500">
                    </div>

                    <!-- API请求示例 -->
                    <div class="mt-8 bg-gray-50 rounded-lg p-6" x-data="{ showExamples: false }">
                        <div class="flex items-center justify-between cursor-pointer" @click="showExamples = !showExamples">
                            <h4 class="text-base font-medium text-gray-900">API请求示例</h4>
                            <button type="button" class="text-gray-500 hover:text-gray-700">
                                <svg class="w-5 h-5 transform transition-transform duration-200" 
                                     :class="{'rotate-180': showExamples}"
                                     fill="none" stroke="currentColor" viewBox="0 0 24 24">
                                    <path stroke-linecap="round" stroke-linejoin="round" stroke-width="2" d="M19 9l-7 7-7-7"></path>
                                </svg>
                            </button>
                        </div>
                        
                        <!-- 示例内容 -->
                        <div x-show="showExamples" 
                             x-transition:enter="transition ease-out duration-200"
                             x-transition:enter-start="opacity-0 transform -translate-y-2"
                             x-transition:enter-end="opacity-100 transform translate-y-0"
                             x-transition:leave="transition ease-in duration-200"
                             x-transition:leave-start="opacity-100 transform translate-y-0"
                             x-transition:leave-end="opacity-0 transform -translate-y-2"
                             class="mt-4">
                            <!-- 启用Token验证时的示例 -->
                            <div class="space-y-3">
                                <p class="text-sm font-medium text-gray-700">启用Token验证时:</p>
                                <div class="bg-gray-900 text-gray-200 rounded-lg p-4 font-mono text-sm overflow-x-auto">
                                    <p class="mb-2"># 获取文章列表</p>
                                    <p>curl -H "Accept: application/json" \</p>
                                    <p class="text-blue-400">     -H "X-API-Token: {{ configs|selectattr('key', 'equalto', 'api_token')|first|attr('value') }}" \</p>
                                    <p>     {{ request.host_url }}</p>
                                    
                                    <p class="mt-4 mb-2"># 获取文章详情</p>
                                    <p>curl -H "Accept: application/json" \</p>
                                    <p class="text-blue-400">     -H "X-API-Token: {{ configs|selectattr('key', 'equalto', 'api_token')|first|attr('value') }}" \</p>
                                    <p>     {{ request.host_url }}article/1 (这里得看你自己定义的文章路径了)</p>
                                    
                                    <p class="mt-4 mb-2"># 获取分类列表</p>
                                    <p>curl -H "Accept: application/json" \</p>
                                    <p class="text-blue-400">     -H "X-API-Token: {{ configs|selectattr('key', 'equalto', 'api_token')|first|attr('value') }}" \</p>
                                    <p>     {{ request.host_url }}category/1?page=1 (这里看你自己定义的分类路径)</p>
                                </div>
                            </div>

                            <!-- 不启用Token验证时的示例 -->
                            <div class="space-y-3 mt-6">
                                <p class="text-sm font-medium text-gray-700">不启用Token验证时:</p>
                                <div class="bg-gray-900 text-gray-200 rounded-lg p-4 font-mono text-sm overflow-x-auto">
                                    <p class="mb-2"># 获取文章列表</p>
                                    <p>curl -H "Accept: application/json" {{ request.host_url }}</p>
                                    
                                    <p class="mt-4 mb-2"># 获取文章详情</p>
                                    <p>curl -H "Accept: application/json" {{ request.host_url }}article/1 (这里得看你自己定义的文章路径了)</p>
                                    
                                    <p class="mt-4 mb-2"># 获取分类列表</p>
                                    <p>curl -H "Accept: application/json" {{ request.host_url }}category/1 (这里看你自己定义的分类路径)</p>
                                </div>
                            </div>

                            <!-- Python示例 -->


                            <!-- 响应格式说明 -->
                            <div class="mt-6">
                                <p class="text-sm font-medium text-gray-700 mb-2">响应格式示例(可以自己在service改):</p>
                                <div class="bg-gray-900 text-gray-200 rounded-lg p-4 font-mono text-sm overflow-x-auto">
                                    <pre class="text-green-400"># 文章列表响应
{
    "total": 100,
    "pages": 10,
    "current_page": 1,
    "articles": [
        {
            "id": 1,
            "title": "文章标题",
            "created_at": "2024-01-01 12:00:00",
            "category": "分类名称",
            "author": "作者",
            "view_count": 100,
            "tags": ["标签1", "标签2"]
        }
    ]
}</pre>
                                </div>
                            </div>
                        </div>
                    </div>
                </div>

                <!-- Gravatar设置 -->
                <div class="space-y-6">
                    <h3 class="text-lg font-medium text-gray-900">Gravatar设置</h3>
                    
                    <!-- Gravatar镜像 -->
                    <div>
                        <label class="block text-sm font-medium text-gray-700 mb-2">
                            Gravatar镜像地址
                        </label>
                        <input type="text" name="config_gravatar_mirror" 
                               value="{{ configs|selectattr('key', 'equalto', 'gravatar_mirror')|first|attr('value') }}"
                               class="w-full px-3 py-2 border rounded-lg focus:outline-none focus:ring-2 focus:ring-blue-500">
                        <p class="mt-1 text-sm text-gray-500">
                            常用镜像: https://weavatar.com/avatar/ 或 https://gravatar.loli.net/avatar/
                        </p>
                    </div>

                    <!-- 默认头像 -->
                    <div>
                        <label class="block text-sm font-medium text-gray-700 mb-2">
                            默认头像样式
                        </label>
                        <select name="config_gravatar_default" id="gravatarStyle"
                                class="w-full px-3 py-2 border rounded-lg focus:outline-none focus:ring-2 focus:ring-blue-500">
                            <option value="mp" {% if configs|selectattr('key', 'equalto', 'gravatar_default')|first|attr('value') == 'mp' %}selected{% endif %}>神秘人(mp)</option>
                            <option value="identicon" {% if configs|selectattr('key', 'equalto', 'gravatar_default')|first|attr('value') == 'identicon' %}selected{% endif %}>抽象图案(identicon)</option>
                            <option value="monsterid" {% if configs|selectattr('key', 'equalto', 'gravatar_default')|first|attr('value') == 'monsterid' %}selected{% endif %}>小怪物(monsterid)</option>
                            <option value="wavatar" {% if configs|selectattr('key', 'equalto', 'gravatar_default')|first|attr('value') == 'wavatar' %}selected{% endif %}>卡通脸(wavatar)</option>
                            <option value="retro" {% if configs|selectattr('key', 'equalto', 'gravatar_default')|first|attr('value') == 'retro' %}selected{% endif %}>复古游戏(retro)</option>
                            <option value="robohash" {% if configs|selectattr('key', 'equalto', 'gravatar_default')|first|attr('value') == 'robohash' %}selected{% endif %}>机器人(robohash)</option>
                            <option value="blank" {% if configs|selectattr('key', 'equalto', 'gravatar_default')|first|attr('value') == 'blank' %}selected{% endif %}>空白(blank)</option>
                        </select>
                        <!-- 添加预览图片 -->
                        <div class="mt-2">
                            <img id="gravatarPreview" src="" alt="头像预览" class="w-16 h-16 rounded-full">
                        </div>
                    </div>
                </div>

                <div class="flex justify-end">
                    <button type="submit"
                            class="px-4 py-2 bg-blue-600 text-white rounded-lg hover:bg-blue-700">
                        保存配置
                    </button>
                </div>
            </form>
        </div>
    </div>
</div>

<script>
    // 添加表单提交处理函数
    function handleSubmit(e) {
        e.preventDefault();
        const form = document.getElementById('configForm');
        
        fetch(window.location.href, {
            method: 'POST',
            body: new FormData(form),
            headers: {
                'X-Requested-With': 'XMLHttpRequest'
            }
        })
        .then(response => response.json())
        .then(data => {
            if(data.success) {
                showAlert(data.message, 'success', '成功');
                setTimeout(() => {
                    window.location.reload();
                }, 300);
            } else {
                showAlert(data.message, 'error', '失败');
            }
        })
        .catch(error => {
            showAlert(data.message + error, 'error', '失败');
        });
        
        return false;
    }

    function generateToken() {
        // 生成更复杂的随机 Token
        const characters = 'ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789';
        let token = '';
        const tokenLength = 32; // 可以根据需要调整长度
        for (let i = 0; i < tokenLength; i++) {
            const randomIndex = Math.floor(Math.random() * characters.length);
            token += characters.charAt(randomIndex);
        }
        // 设置到输入框
        const inputElement = document.querySelector('input[name="config_api_token"]');
        if (inputElement) {
            inputElement.value = token;
        }
    }


    // 处理头像预览
    function updateGravatarPreview() {
        const style = document.getElementById('gravatarStyle').value;
        const mirror = document.querySelector('input[name="config_gravatar_mirror"]').value || 'https://www.gravatar.com/avatar/';
        const hash = '00000000000000000000000000000000'; // 默认hash
        const previewUrl = `${mirror}${hash}?d=${style}&s=128`;
        document.getElementById('gravatarPreview').src = previewUrl;
    }

    // 监听样式选择变化
    document.getElementById('gravatarStyle').addEventListener('change', updateGravatarPreview);

    // 监听镜像地址变化
    document.querySelector('input[name="config_gravatar_mirror"]').addEventListener('input', updateGravatarPreview);

    // 页面加载时初始化预览
    document.addEventListener('DOMContentLoaded', updateGravatarPreview);
</script>
{% endblock %} 